<script setup lang="ts">
import { sendRequest } from '@/utils/api'
import type { HttpResponse } from '@/utils/http'
import {
  NUpload,
  NUploadFileList,
  NUploadTrigger,
  useMessage,
  type UploadCustomRequestOptions,
  type UploadFileInfo
} from 'naive-ui'

defineProps<{
  fileList?: UploadFileInfo[]
  disabled?: boolean
}>()

defineEmits<{
  (event: 'update:file-list', list: UploadFileInfo[]): void
}>()

const message = useMessage()

const handleUpload = async ({
  file,
  onFinish,
  onError,
  onProgress
}: UploadCustomRequestOptions) => {
  try {
    const formData = new FormData()
    formData.append('file', file.file as File)
    const [error, res] = await sendRequest<HttpResponse>({
      module: 'upload',
      api: 'uploadFile',
      override: {
        data: formData,
        headers: {
          'Content-Type': 'multipart/form-data'
        },
        onUploadProgress: (e) => {
          onProgress({ percent: e.progress || 0 })
        }
      }
    })
    if (error) throw error
    if (res.code !== 0) throw new Error(res.msg)
    // @ts-ignore
    if (file.file) file.file.remoteId = res.data.fileId
    onFinish()
    message.success(res.msg)
  } catch (error: any) {
    onError()
    message.error(error.message)
  }
}
</script>

<template>
  <NUpload
    abstract
    :custom-request="handleUpload"
    :file-list="fileList"
    :disabled="disabled"
    @update:file-list="$emit('update:file-list', $event)"
  >
    <NUploadTrigger
      #="payload"
      abstract
    >
      <slot
        v-bind="payload"
        name="trigger"
      ></slot>
    </NUploadTrigger>
    <NUploadFileList :disabled="disabled" />
  </NUpload>
</template>
